package other.system.client.apitool;

import com.alibaba.fastjson.JSONObject;
import com.rkhd.platform.sdk.exception.CacheException;
import com.rkhd.platform.sdk.exception.CustomConfigException;
import com.rkhd.platform.sdk.http.CommonData;
import com.rkhd.platform.sdk.http.CommonHttpClient;
import com.rkhd.platform.sdk.http.HttpResult;
import com.rkhd.platform.sdk.log.Logger;
import com.rkhd.platform.sdk.log.LoggerFactory;
import com.rkhd.platform.sdk.service.CacheService;
import com.rkhd.platform.sdk.service.CustomConfigService;
import org.apache.commons.lang.StringUtils;
import other.system.client.util.ResultBody;

import java.util.HashMap;
import java.util.Map;

/**
 * @Description  极客空间 sap 中间件对接
 * @Author 黎炎松
 * 2024-07-09 16:32
 */
public class SAPClientUtils {
    private static String BASE_URL = "https://geek.tcl.com"; // 正式域名
    //private static String BASE_URL = "http://kong.poros-platform-geek.10.74.162.19.sit.docker.tcl.com"; // 测试域名
    private static String GET_TOKEN_URL = BASE_URL + "/api/poros-authcenter/oauth/token"; // 获取token
    public static String GET_PRODUCT_URL = BASE_URL + "/api/geekmatrix/sap/query"; // 获取产品数据 (产品)
    public static String GET_ACCOUNT_URL = BASE_URL + "/api/geekmatrix/sap/customerInfo"; // 获取客户数据_SAP编码
    public static String INVOICE_URL = BASE_URL + "/api/geekmatrix/sap/invoice"; // 开票
    public static String PAYMENT_URL = BASE_URL + "/api/geekmatrix/sap/receivedPayments"; // 回款、认领
    private static final Logger logger = LoggerFactory.getLogger();
    private static final CacheService cacheService = CacheService.instance();
    private static final String TOKEN_KEY = "SAP_TOKEN";

    // k3 信息配置
    public static Map<String, String> sapConfig = new HashMap<>();

    static {
        try {
            CustomConfigService instance = CustomConfigService.instance();
            sapConfig = instance.getConfigSet("sapConfig");
            if (sapConfig == null) {
                sapConfig = new HashMap<>();
            }
        } catch (CustomConfigException e) {
            throw new RuntimeException(e);
        }
    }


    public static void main(String[] args) throws CustomConfigException {
    }

    /**
     * 发送post请求
     * @param reqData
     * @param reqUrl
     * @return
     */
    public static ResultBody sendPost(JSONObject reqData, String reqUrl, String token) throws CacheException {

        if (StringUtils.isBlank(token)) {
            token = getToken();
        }

        CommonData build = CommonData.newBuilder().callString(reqUrl)
                .callType("POST")
                .header("Authorization", "bearer " + token)
                .body(reqData.toJSONString())
                .formType("application/json")
                .build();
        HttpResult execute = CommonHttpClient.instance(1000 * 60, 1000 * 60).execute(build);
        String result = execute.getResult();
        //System.out.println("result = " + result);
        JSONObject response = JSONObject.parseObject(result);
        Integer code = response.getInteger("code");
        if (code != 0) {
            // 判断是否是缓存过期
            if (code == 401) {
                // 重新发起请求
                logger.error("SAP token过期，重新发起请求");
                cacheService.delete(TOKEN_KEY);
                return sendPost(reqData, reqUrl, "");
            } else {
                String errorMsg = response.getString("msg");
                return ResultBody.error(errorMsg);
            }
        }

        Object data = response.get("data");
        return ResultBody.success(data);
    }

    // 判断是否能正常解析
    public static boolean isJSON(String str) {
        boolean result = false;
        try {
            JSONObject.parseObject(str);
            result = true;
        } catch (Exception e) {
            result = false;
        }
        return result;
    }


    public static String getToken() throws CacheException {

        // 判断缓存中是否存在
        String token = cacheService.get(TOKEN_KEY);
        if (StringUtils.isNotBlank(token)) {
            logger.info("获取缓存token");
            return token;
        }

        String username = sapConfig.getOrDefault("username", "pmstest");
        String clientId = sapConfig.getOrDefault("client_id","pmstest");
        String clientSecret = sapConfig.getOrDefault("client_secret","pmstest");
        String reqParams = String.format("?grant_type=username&username=%s&client_id=%s&client_secret=%s", username, clientId, clientSecret);

        // 发送请求
        CommonData build = CommonData.newBuilder().callString(GET_TOKEN_URL + reqParams)
                .callType("POST")
                .build();

        HttpResult execute = CommonHttpClient.instance().execute(build);
        String result = execute.getResult();
        logger.info("result ==> " + result);

        // 判断是json 且有 access_token 代表获取成功
        if (!isJSON(result)) {
            throw new RuntimeException("获取token异常:" + result);
        }

        JSONObject response = JSONObject.parseObject(result);
        String accessToken = response.getString("access_token");
        if (StringUtils.isBlank(accessToken)) {
            throw new RuntimeException("获取token异常:" + result);
        }

        // 设置缓存值
        cacheService.set(TOKEN_KEY, accessToken);
        return accessToken;
    }


}
